package servlet.man;

import bean.Manager;
import bean.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import service.UserService;
import service.UserServiceImpl;
import servlet.hou.HouLoginServlet;
import utils.JwtUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 李夏
 * @version 1.0
 */

//管理员登陆
@WebServlet("/man/login")
public class ManLoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("=================管理员登录==================");
        //根据输入框标签的name属性值去获取登录名和密码
//        String manName=request.getParameter("manName");
        String manPassword=request.getParameter("password");

        int manId= Integer.parseInt(request.getParameter("manId"));
        //记住密码


        UserService userService=new UserServiceImpl();
        //去查询用户输入的登录名和密码是否正确
        Manager manager=userService.manFindByPasswordAndId(manPassword,manId);

        if(manager==null){
            //用户输入的名字或密码错误,即没找到该用户，跳转到登录页面，并给予提示信息
            Result result = new Result();
            result.failToLogin();
            ObjectMapper objectMapper = new ObjectMapper();
            String str = objectMapper.writeValueAsString(result);
            response.setContentType("application/json;charset=utf8");
            response.getWriter().print(str);
            System.out.println(str);


        }else{
            //生成token
            Map<String,Object> claim = new HashMap<>();
            claim.put("manId",manager.getManId());
            claim.put("manName",manager.getManName());
            Result result = new Result();
            result.success(JwtUtils.genToken(claim));
            ObjectMapper objectMapper = new ObjectMapper();
            String str = objectMapper.writeValueAsString(result);
            response.setContentType("application/json;charset=utf8");
            response.getWriter().print(str);
            //说明用户的名字和密码正确，登录成功

            System.out.println("================跳转到管理员主页面=============");
            new HouLoginServlet().insertOp("管理员"+manager.getManName(),manager.getManId(),"管理员"+manager.getManName()+"登陆了系统");


        }


    }
}
